'use strict';
const Service = require('egg').Service;

class ManageService extends Service {
    async every() {
        const { app, ctx } = this;
        const Op = app.Sequelize.Op;
        return await ctx.model.Warranty.findAndCountAll({
            where:{
                upt_act: { [Op.ne]: 'D' },
            },
            attributes:['created_at']
        });
        
    }
    //查询当天的保修
    async today() {
        const { app, ctx } = this;
        const Op = app.Sequelize.Op;
        const time = new Date().toLocaleDateString()
        const time2 = time.split('/')
        const time3 = time2[0] + '-0' + time2[1] + '-0' + time2[2] + ' 00:00:00'
        return await ctx.model.Warranty.findAndCountAll({
            where:{
                upt_act: { [Op.ne]: 'D' },
                created_at: {
                    [Op.gt]: time3
                }
            },
            order: [['created_at', 'desc']],
            include: {
                model: ctx.model.Sys.User,
                attributes: ['name', ],
                // where:sewhere
            },
        });
        
    }

  // 查询所有
  async page(query) {
    const { app, ctx } = this;
    const { limit, page } = query;
    const Op = app.Sequelize.Op;
    const where = { upt_act: { [Op.ne]: 'D' } };
    // const { userid }=ctx.state.user;
    // const user = await ctx.model.Sys.User.findOne({
    //   include:{
    //     model:ctx.model.Sys.Role,
    //     attributes:['name']
    //   },
    //   where:{id:userid},
    //   attributes:['id','username']
    // });
    // const name = user.dataValues.sys_roles[0].dataValues.name
    // var sewhere={};
    // if(name !='超级管理员' && name != '维修工'){
    //   sewhere={
    //     id:userid
    //   }
    // }
    if (query.name) {
      where.name = { [Op.like]: `%${query.name}%` };
    }
    if (query.error) {
      where.error = { [Op.like]: `%${query.error}%` };
    }
    if (query.status) {
      where.status = { [Op.like]: `%${query.status}%` };
    }
    if (query.equip_status) {
      where.equip_status = { [Op.like]: `%${query.equip_status}%` };
    }
    return await ctx.model.Warranty.findAndCountAll({
      distinct: true, // 不加distinct，count和实际不符
      where,
      offset: (page - 1) * limit,
      limit: parseInt(limit),
      order: [['created_at', 'desc']],
      include: {
        model: ctx.model.Sys.User,
        attributes: ['id', 'name'],
        // where:sewhere
      },
    });
  }
  async create(body) {
    const { app, ctx } = this;
    const { userid } = ctx.state.user;
    body.created_id = userid;
    body.updated_id = userid;
    body.status = "待处理";
    const user = await ctx.model.Sys.User.findByPk(userid);
    //找出设备编号
    const equip = await ctx.model.Manage.findAll({
      where: {
        num: body.equip_num,

      },
      attributes: ['name']
    });
    body.report_name = user.name;
    body.name = equip[0].name;
    var date = new Date();
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString();
    var day = (date.getDate()).toString();
    var hour = (date.getHours()).toString();
    var minute = (date.getMinutes()).toString();
    var second = (date.getSeconds()).toString();
    if (month.length == 1) {
      month = "0" + month;
    }
    if (day.length == 1) {
      day = "0" + day;
    }
    var dateTime = year + month + day + hour + minute + second;
    body.num = 'RX' + dateTime + Math.floor(Math.random() * 10)
    try {
        return await ctx.model.transaction(async t => {
        // 创建用户信息
        await ctx.model.Warranty.create(body, { transaction: t });
        await ctx.model.Manage.update({ status:body.equip_status },{
          where:{
            num:body.equip_num
          }
        })
        return { success: true };
      });
    } catch (error) {
      console.log(error);
      return { success: false };
    }
  }
  async update(body) {
    const { app, ctx } = this;
    const { userid } = ctx.state.user;
    body.updated_at = ctx.helper.formatTime(new Date());
    body.updated_id = userid;
    body.upt_act = 'U';
    try {
      return await ctx.model.transaction(async t => {

        // 更新设备信息
        await ctx.model.Warranty.update(body, {
          transaction: t,
          where: {
            num: body.num,
          },
        });
        return { success: true };
      });
    } catch (error) {
      console.log(error);
      return { success: false };
    }
  }
  async delete({ num }) {
    const { ctx } = this;
    const body = {
      upt_act: 'D',
      updated_at: ctx.helper.formatTime(new Date()),
      updated_id: ctx.state.user.userid,
    };
    try {
      return await ctx.model.transaction(async t=>{
        await ctx.model.Warranty.update(body, {
          where: { num },
        });
        await ctx.model.Maintain.update(body,{
          where:{ num }
        })
        return true;
      })
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  async checkrepair({ equip_num }){
    const { ctx } =this;
    const body = {
      upt_act: 'U',
      updated_at: ctx.helper.formatTime(new Date()),
      updated_id: ctx.state.user.userid,
      status:'已验收'
    };
    console.log(equip_num);
    try{
      return await ctx.model.transaction(async t=>{
        await ctx.model.Warranty.update(body,{
          where:{ 
            equip_num
          },
        });
        await ctx.model.Maintain.update(body,{
          where:{
            equip_num
          }
        })
        return { success: true };
      })
    } catch (error) {
      console.log(error);
      return { success: false };
    }
  }
}
module.exports = ManageService;